package com.zym.init.controller.backend;

import com.zym.init.core.annotation.Anonymous;
import com.zym.init.core.annotation.ApiBackendRestController;
import com.zym.init.core.controller.BaseController;
import com.zym.init.core.domain.AjaxResult;
import com.zym.init.model.po.UserPo;
import com.zym.init.model.query.UserQuery;
import com.zym.init.service.LoginService;
import com.zym.init.service.UserService;
import com.zym.init.core.utils.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.validation.constraints.NotEmpty;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.Map;

/**
 * 登录控制器
 */
@Validated
@ApiBackendRestController
public class LoginController extends BaseController {

    private final UserService userService;
    private final LoginService loginService;

    public LoginController(UserService userService, LoginService loginService) {
        this.userService = userService;
        this.loginService = loginService;
    }

    /**
     * 注册
     *
     * @param query 用户对象
     * @return 响应结果
     */
    @Anonymous
    @PostMapping("/register")
    public AjaxResult register(@RequestBody @Validated(value = UserQuery.Add.class) UserQuery query) {
        if (userService.add(query)) {
            return success("注册成功");
        }
        return fail("注册失败，请联系管理员");
    }

    /**
     * 登录
     *
     * @param username 用户名
     * @param password 密码
     * @return 响应结果
     */
    @Anonymous
    @GetMapping("/login")
    public AjaxResult login(
            @NotEmpty(message = "用户名不能为空") String username,
            @NotEmpty(message = "密码不能为空") String password
    ) {
        return success("登录成功", Map.of("token", loginService.login(username, password)));
    }


    /**
     * 获取当前登录用户信息
     *
     * @return 响应结果
     */
    @GetMapping("/getLoginUser")
    public AjaxResult getLoginUser() {
        UserPo userPo = SecurityUtils.getLoginUser().getUserPo();
        return success(userPo.toVo());
    }

    /**
     * 注销登录
     *
     * @return 响应结果
     */
    @GetMapping("/logout")
    public AjaxResult logout() {
        loginService.logout();
        return success("退出登录成功");
    }


    /**
     * 角色测试
     *
     * @return 响应结果
     */
    @PreAuthorize("@ss.hasRole('super-admin')")
    @GetMapping("/isAdmin")
    @Operation(summary = "角色测试")
    public AjaxResult isAdmin() {
        return success("管理员权限测试");
    }

    /**
     * 权限测试
     *
     * @return 响应结果
     */
    @PreAuthorize("@ss.hasPermission('system:test:1')")
    @GetMapping("/checkPermission")
    @Operation(summary = "权限测试")
    public AjaxResult checkPermission() {
        return success("用户权限测试");
    }

}
